Grokking Tree Coding Patterns for Interviews
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Course Overview
Introduction to Tree
Types of Tree
BST Traversal Techniques
BST Operations
Introduction to Level Order Traversal Pattern
Reverse Level Order Traversal (easy)
Solution: Reverse Level Order Traversal
Find Largest Value in Each Tree Row (medium)
Solution: Find Largest Value in Each Tree Row
Maximum Width of Binary Tree (medium)
Solution: Maximum Width of Binary Tree
Maximum Level Sum of a Binary Tree (medium)
Solution: Maximum Level Sum of a Binary Tree
Zigzag Traversal (medium)
Solution: Zigzag Traversal
Even Odd Tree (medium)
Solution: Even Odd Tree
N-ary Tree Level Order Traversal (hard)
Solution: N-ary Tree Level Order Traversal
Introduction to Tree Depth Pattern
Maximum Depth (or Height) of Binary Tree (easy)
Solution: Maximum Depth (or Height) of Binary Tree
Minimum Depth of a Binary Tree (easy)
Solution: Minimum Depth of a Binary Tree
Balanced Binary Tree (easy)
Solution: Balanced Binary Tree
Tree Diameter (easy)
Solution: Tree Diameter
Maximum Depth of N-ary Tree (easy)
Solution: Maximum Depth of N-ary Tree
Find maximum depth of subtree (medium)
Solution: Find maximum depth of subtree
Root to Leaf Path Pattern (medium)
Introduction to Root to Leaf Path Pattern
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Sum of Root To Leaf Binary Numbers (easy)
Solution: Sum of Root To Leaf Binary Numbers
Insufficient Nodes in Root to Leaf Paths (medium)
Solution: Insufficient Nodes in Root to Leaf Paths
Smallest String Starting From Leaf (medium)
Solution: Smallest String Starting From Leaf
Pseudo-Palindromic Paths in a Binary Tree (medium)
Solution: Pseudo-Palindromic Paths in a Binary Tree
All Paths for a Sum (medium)
Solution: All Paths for a Sum
Sum of Path Numbers (medium)
Solution: Sum of Path Numbers
Path With Given Sequence (medium)
Solution: Path With Given Sequence
Count Paths for a Sum (medium)
Solution: Count Paths for a Sum
Leaf Processing Pattern (medium)
Introduction to Leaf Processing Pattern
Sum of Left Leaves (easy)
Solution: Sum of Left Leaves
Leaf-Similar Trees (easy)
Solution: Leaf-Similar Trees
Check if all leaves are at same level (medium)
Solution: Check if all leaves are at same level
Delete Leaves With a Given Value (medium)
Solution: Delete Leaves With a Given Value
Deepest Leaves Sum (medium)
Solution: Deepest Leaves Sum
Introduction to Tree View Pattern
Right View of a Binary Tree (medium)
Solution: Right View of a Binary Tree
Top View Of the Binary Tree (medium)
Solution: Top View Of the Binary Tree
Bottom View Of the Binary Tree (medium)
Solution: Bottom View Of the Binary Tree
Boundary of Binary Tree (medium)
Solution: Boundary of Binary Tree
Introduction to Comparison of Two Trees Pattern
Symmetric Tree (easy)
Solution: Symmetric Tree
Mirror Image Trees (medium)
Solution: Mirror Image Trees
Subtree of Another Tree (easy)
Solution: Subtree of Another Tree
Isomorphic Trees (medium)
Solution: Isomorphic Trees
Introduction to Serialize and Deserialize Tree Pattern
Serialize and Deserialize BST (medium)
Solution: Serialize and Deserialize BST
Verify Preorder Serialization of a Binary Tree (medium)
Solution: Verify Preorder Serialization of a Binary Tree
Create Binary Tree From Descriptions (medium)
Solution: Create Binary Tree From Descriptions
Serialize and Deserialize N-ary Tree (hard)
Solution: Serialize and Deserialize N-ary Tree
Solution: Deepest Leaves Sum

Problem Statement

Given a root node of the binary tree, return the sum of all values located at the deepest leaves of a binary tree.

Examples

  • Example 1:
    • Input: root = [1,2,3,4,5,null,7]
Image
  • Expected Output: 16

  • Justification: The deepest level contains the nodes with values 4, 5, and 7, and their sum is 16.

  • Example 2:

    • Input: root = [6,2,8,null,null,7,9,null,null,null,10]
Image
  • Expected Output: 10

  • Justification: The deepest level contains only one node with the value 10, thus the sum is 10.

  • Example 3:

    • Input: root = [1,null,2,null,3,null,4]
Image
  • Expected Output: 4
  • Justification: The binary tree's deepest level has a single node with the value 4. Since it's the only node at that level, the sum is 4.

Solution

To solve this problem, the approach involves a breadth-first search (BFS) traversal of the binary tree. This method is chosen because BFS explores the tree level by level, starting from the root, making it efficient to identify the deepest leaves. By utilizing a queue to keep track of nodes and their levels, we can process each level of the tree sequentially. Once we reach the last level, we calculate the sum of all nodes at that level.

This approach is effective because it ensures that we visit all nodes in the tree while maintaining a clear distinction between different levels. By doing so, we can easily identify when we've reached the deepest level and then sum up the values of the nodes at this level. It is also efficient, as each node is visited exactly once, and no unnecessary computations are done.

Step-by-Step Algorithm

  1. Check for Empty Tree:

    • If the root node is null, return 0 as the tree is empty, and there are no leaves to sum.
  2. Initialize Queue and Variables:

    • Initialize a queue to hold the nodes of the tree along with their level. Start by enqueuing the root node.
    • Initialize levelSum to 0. This variable will hold the sum of the values of the nodes at the current (deepest) level.
  3. Breadth-First Search (BFS) Loop:

    • While the queue is not empty, perform the following steps to process each level of the tree:
      • Note the size of the queue at the start of the loop iteration. This size represents the number of nodes at the current level, as all nodes in the queue are from the same level.
      • Reset levelSum to 0 at the start of processing a new level.
      • Loop through the nodes at the current level (using the noted size of the queue to ensure only nodes of the current level are processed):
        • Dequeue a node from the queue.
        • Add the value of the dequeued node to levelSum.
        • If the dequeued node has a left child, enqueue this child.
        • If the dequeued node has a right child, enqueue this child.
  4. Return Sum of Deepest Leaves:

    • After the loop ends (i.e., the queue is empty, and all levels have been processed), levelSum contains the sum of the values of the nodes at the deepest level of the tree.
    • Return levelSum.

Algorithm Walkthrough

Let's consider the Input: root = [1,2,3,4,5,null,7]

  1. Initialization:

    • The tree is not empty, so we proceed.
    • Queue = [1], levelSum = 0.
  2. First Level Processing (Root Level):

    • Queue size at start = 1 (contains root node 1).
    • levelSum reset to 0.
    • Dequeue 1: Queue = [], levelSum = 1 (value of node 1).
    • Enqueue children of 1: Queue = [2, 3].
  3. Second Level Processing:

    • Queue size at start = 2 (contains nodes 2 and 3).
    • levelSum reset to 0.
    • Dequeue 2: Queue = [3], levelSum = 2 (value of node 2).
    • Enqueue children of 2: Queue = [3, 4, 5].
    • Dequeue 3: Queue = [4, 5], levelSum = 5 (2 + value of node 3).
    • Enqueue right child of 3 (node 7): Queue = [4, 5, 7].
  4. Third Level Processing:

    • Queue size at start = 3 (contains nodes 4, 5, and 7).
    • levelSum reset to 0.
    • Dequeue 4: Queue = [5, 7], levelSum = 4.
    • No children to enqueue.
    • Dequeue 5: Queue = [7], levelSum = 9 (4 + value of node 5).
    • No children to enqueue.
    • Dequeue 7: Queue = [], levelSum = 16 (9 + value of node 7).
    • No children to enqueue.
  5. Return Sum:

    • With the queue empty and all levels processed, the loop ends.
    • levelSum is 16, which is the sum of the values of the nodes at the deepest level.
    • Return 16.

Code

Java

. . . .

Complexity Analysis

Time Complexity

The time complexity is , where (N) is the number of nodes in the binary tree. This is because each node in the tree is visited exactly once during the BFS traversal.

Space Complexity

The space complexity is , where (W) is the maximum width of the tree. This occurs at the level with the most nodes, which dictates the maximum number of elements that can be stored in the queue at any time. In the worst case, a binary tree could be a complete binary tree, where the last level has nodes, making the space complexity in such scenarios.

Deepest Leaves Sum (medium)
Introduction to Tree View Pattern
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity